import { PSModelServiceImpl } from '../../../psmodel-service-impl';

/**
 * 模型实例管理帮助类
 *
 * @author chitanda
 * @date 2021-05-12 16:05:22
 * @export
 * @class ModelInstanceHelp
 */
export class ModelInstanceHelp {
  /**
   * 默认模型服务
   *
   * @private
   * @type {PSModelServiceImpl}
   */
  private defaultModelService: PSModelServiceImpl;

  /**
   * 根据实例id获取对应模型服务
   *
   * @author chitanda
   * @date 2022-12-22 15:12:03
   * @return {*}  {PSModelServiceImpl}
   */
  getModelService(): PSModelServiceImpl {
    return this.defaultModelService;
  }

  /**
   * 安装应用数据
   *
   * @author chitanda
   * @date 2021-04-10 11:04:20
   * @param {PSModelServiceImpl} modelService 指定模型根实例模型服务
   * @param {(modelPath: string) => Promise<IModel>} getModelJson 模型JSON文件请求
   * @return {*}  {Promise<void>}
   */
  install(
    modelService: PSModelServiceImpl,
    getModelJson: (modelPath: string) => Promise<IModel>,
  ): Promise<void> {
    this.defaultModelService = modelService;
    this.defaultModelService.getModelJson = getModelJson;
    return this.initApp(modelService);
  }

  /**
   * 初始化应用
   *
   * @protected
   * @param {PSModelServiceImpl} modelService
   * @return {*}  {Promise<void>}
   */
  protected async initApp(modelService: PSModelServiceImpl): Promise<void> {
    await modelService.app.fill();
    await modelService.loadLanguage();
    this.installCache(modelService);
  }

  /**
   * 安装应用加载缓存数据
   *
   * @protected
   */
  protected installCache(modelService: PSModelServiceImpl): void {
    const app = modelService.app;
    // 填充视图缓存，避免与子不一样导致报错
    app.getAllPSAppViews();
    // 填充应用实体，避免与子不一样导致报错
    app.getAllPSAppDataEntities();
    const cache = app.M?.cache;
    if (cache) {
      // 安装视图缓存
      const views: IModel[] = cache.getPSAppViews;
      if (views?.length > 0) {
        views.forEach((item: IModel) => {
          const obj = modelService.getPSModel4(
            app,
            'app.view.IPSAppView',
            item,
          );
          obj.init(modelService, app, item.dynaModelFilePath, item);
        });
      }
      // 安装实体缓存
      const entities: IModel[] = cache.getPSAppDataEntities;
      if (entities?.length > 0) {
        entities.forEach((item: IModel) => {
          modelService.getPSModel4(
            app,
            'app.dataentity.IPSAppDataEntity',
            item,
          );
        });
      }
    }
  }
}
